<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/src/css/main.css" media="all">
</head>

<body>
    <div id="layui-body-content" class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <form class="layui-form layui-form-pane">
                    <div class="gridAuto">
                        <div class="layui-form-item">
                            <label class="layui-form-label">区划名称</label>
                            <div class="layui-input-block">
                                <div class="layui-input-wrap">
                                    <input type="text" name="name" id="name" placeholder="请输入区划名称" lay-affix="clear"
                                        autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-btn-container selectFormBox">

                        <button class="layui-btn layuiadmin-btn-area-list  layui-btn-sm" type="button"
                            lay-on="Yjsearch">
                            <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>查询
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                            <i class="layui-icon layui-icon-fonts-clear"></i>清空
                        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-normal" type="button" lay-on="Yjadd">
                            <i class="layui-icon layui-icon-add-circle layuiadmin-button-btn"></i>添加
                        </button>
                    </div>
                </form>
                <div style="padding-left: 10px; padding-bottom: 10px; padding-top: 0px;" id="divpath">
                    <a id="0" data-type="next" class="layuiadmin-btn-area-list layui-a-tips">所有区划>></a>
                </div>
                <table id="LAY-app-area-list" lay-filter="LAY-app-area-list"></table>
                <input type="hidden" id="pid" />
                <input type="hidden" id="parent_path" />
                <script type="text/html" id="ID-table-status-switch">
                    <input type="checkbox" name="status" value="{{= d.id }}" title="启用|禁用" lay-skin="switch" lay-filter="demo-templet-status" {{= d.status == '0' ? "checked" : "" }}>
                  </script>
                <script type="text/html" id="tableoption">
                    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="next"><i class="layui-icon layui-icon-edit"></i>下一级</a>
                </script>
                <script id="LAY-app-area-toolbar" type="text/html">
                    <div class="layui-clear-space">
                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                    </div>
                </script>
            </div>
        </div>
    </div>

    <script src="/layui/layui.js"></script>
    <script>
        layui.config({
            base: '/src/'
        }).use('index', function () {
            var table = layui.table,
                $ = layui.$,
                $body = $('body'),
                main = layui.main,
                dropdown = layui.dropdown,
                form = layui.form,
                form2 = top.layui.form,
                util = layui.util,
                layer = layui.layer,
                layer2 = top.layui.layer,
                admin = layui.admin;
            // 区划
            let breadcrumb = [{ id: 0, name: '所有区划', path: '0' }];
            function updateBreadcrumb() {
                let html = '';
                breadcrumb.forEach((item, index) => {
                    if (index > 0) html += ' >> ';
                    html += `<a class="layuiadmin-btn-area-list layui-a-tips" 
                    data-id="${item.id}" 
                    data-index="${index}"
                    data-path="${item.path}" 
                    style="cursor: pointer;">${item.name}</a>`;
                });
                $('#divpath').html(html);
            }
            // 点击路径导航时触发
            $('#divpath').on('click', 'a', function () {
                const index = $(this).data('index');
                const item = breadcrumb[index];

                // 截断面包屑到当前点击的层级
                breadcrumb = breadcrumb.slice(0, index + 1);

                // 更新 pid 和 parent_path
                pid = item.id;
                parent_path = item.path;

                // 同步到隐藏字段
                $("#pid").val(pid);
                $("#parent_path").val(parent_path);

                // 重新加载表格
                table.reload('LAY-app-area-list', { page: { curr: 1 }, where: { pid: pid } });

                // 更新面包屑显示
                updateBreadcrumb();
            });
            var pid = 0;
            var parent_path = "0"; // 初始路径为根节点
            $("#parent_path").val(parent_path);
            updateBreadcrumb(); // 初始化路径显示
            table.render({
                elem: '#LAY-app-area-list',
                url: admin.getUrl('sysarea/getarealist'),
                where: {
                    pid: pid,
                },
                cols: [[
                    {
                        type: 'numbers',
                        fixed: 'left',
                        title: '序号'
                    }, {
                        field: 'name',
                        title: '区划名称',
                        sort: true
                    }, {
                        field: 'code',
                        title: '区划代码',
                        sort: true
                    }, {
                        field: 'abbname',
                        title: '简称',
                        sort: true
                    }, {
                        field: 'order_num',
                        title: '排序',
                        sort: true,
                        width: 85,
                    }, {
                        title: '状态',
                        width: 100,
                        templet: '#ID-table-status-switch'
                    }, {
                        title: '下一级',
                        width: 100,
                        align: 'center',
                        fixed: 'right',
                        toolbar: '#tableoption'
                    }, {
                        title: '操作',
                        width: 120,
                        align: 'center',
                        fixed: 'right',
                        toolbar: '#LAY-app-area-toolbar'
                    }]
                ],
                height: 'full-200',
                page: true,
                limit: 30,
                done: function (res) {
                }
            });
            function returnPopStr(type) {
                // type 0-添加 1-查看 2-编辑
                return `
            <form class="layui-form" action="" lay-filter="${type == 0 ? 'addForm' : (type == 1 ? 'seeForm' : 'editForm')}">
                <ul class="layui-form layui-form-pane" style="margin: 15px;">
                            <li class="layui-form-item">
                                <label class="layui-form-label">区划名称</label>
                                <div class="layui-input-block">
                                    <input class="layui-input" lay-verify="required" name="name" >
                                </div>
                            </li>
                            <li class="layui-form-item">
                                <label class="layui-form-label">区划代码</label>
                                <div class="layui-input-block">
                                    <input class="layui-input" lay-verify="required" name="code" >
                                </div>
                            </li>
                            <li class="layui-form-item">
                                <label class="layui-form-label">简称</label>
                                <div class="layui-input-block">
                                    <input class="layui-input" name="abbname">
                                </div>
                            </li>
                            <li class="layui-form-item">
                                <label class="layui-form-label">状态</label>
                               <div class="layui-input-block">
                                <input type="checkbox" name="status" lay-skin="switch" lay-filter="switchTest" title="启用|禁用">
                               </div>
                            </li>
                            <li class="layui-form-item">
                                <label class="layui-form-label">排序</label>
                                <div class="layui-input-block">
                                    <input type="number" lay-affix="number" min="0" name="order_num" value="0" class="layui-input" >
                                </div>
                            </li>
                             <li class="layui-form-item">
                                <label class="layui-form-label">备注</label>
                                <div class="layui-input-block">
                                    <textarea name="memo" placeholder="请输入备注" class="layui-textarea"></textarea>
                                </div>
                            </li>
                            <li class="layui-form-item" style="text-align:center;">
                        ${type == 0 ? '<button type="button" lay-submit lay-filter="addarea" class="layui-btn">添加</button>'
                        : (type == 1 ? ''
                            : '<button type="button" lay-submit lay-filter="editarea" class="layui-btn">保存</button>')}
                    </li>
                </ul>
            </form>`
            }
            // 状态 - 开关操作
            form.on('switch(demo-templet-status)', function (obj) {
                var value = this.value;
                var id = value;
                var status = this.checked ? 0 : 1;
                admin.req({
                    url: 'sysarea/updateStatusByID',
                    data: JSON.stringify({
                        id: Number(id),
                        status: Number(status)
                    }),
                    contentType: 'application/json', // 强制 JSON 格式
                    type: 'put',
                    done: function (res) {
                        if (res.successful) {
                            main.msg_success('修改成功！');
                        } else {
                            main.msg_error(res.msg);
                        }
                    }
                });
            });
            // 统一事件处理 (按钮)
            util.on({
                Yjsearch: function () {
                    var keywords = $("#name").val();
                    table.reload('LAY-app-area-list', {
                        where: {
                            pid: pid,
                            name: keywords
                        },
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                },
                Yjadd: function () {
                    layer2.open({
                        type: 1,
                        resize: false,
                        shadeClose: true,
                        area: ['800px', '600px'],
                        title: '添加区划',
                        content: returnPopStr(0),
                        success: function (layero, index) {
                            layero.find('.layui-layer-content').css('overflow', 'visible');
                            form2.render().on('submit(addarea)', function (data) {
                                // 从隐藏字段获取最新的 parent_path
                                const currentParentPath = $("#parent_path").val();
                                data.field.parent_path = currentParentPath;
                                data.field.status = data.field.status == 'on' ? 0 : 1;
                                data.field.order_num = data.field.order_num;
                                data.field.pid = pid;
                                data.field.depth = currentParentPath.split(',').length - 1;
                                admin.req({
                                    url: 'sysarea/addarea',
                                    data: JSON.stringify(data.field),
                                    contentType: 'application/json',
                                    type: 'post',
                                    done: function (res) {
                                        if (res.successful) {
                                            main.msg_success('添加成功！');
                                            table.reload('LAY-app-area-list');
                                        } else {
                                            main.msg_error(res.msg);
                                        }
                                        layer2.close(index)
                                    }
                                });
                            });
                        }
                    });
                }
            });

            // 触发表格单元格工具事件
            table.on('tool(LAY-app-area-list)', function (obj) { // 双击 toolDouble
                var data = obj.data; // 获得当前行数据
                if (obj.event === 'edit') {
                    layer2.open({
                        title: '编辑 - ' + data.name,
                        type: 1,
                        area: '420px',
                        content: returnPopStr(2),
                        success: function (layero, index) {
                            form2.render().on('submit(editarea)', function (obj) {
                                obj.field.depth = data.depth;
                                obj.field.id = data.id;
                                obj.field.status = obj.field.status === 'on' ? 0 : 1;
                                obj.field.pid = data.pid;
                                const currentParentPath = $("#parent_path").val();
                                obj.field.parent_path = currentParentPath;;
                                admin.req({
                                    url: 'sysarea/updatearea',
                                    data: JSON.stringify(obj.field),
                                    contentType: 'application/json',
                                    type: 'PUT',
                                    done: function (res) {
                                        if (res.successful) {
                                            main.msg_success('修改成功！');
                                            table.reload('LAY-app-area-list');
                                        } else {
                                            main.msg_error('修改失败！');
                                        }
                                        layer2.close(index)
                                    }
                                });
                            });
                            form2.val('editForm', {
                                "name": data.name, // "name": "value"
                                "code": data.code,
                                "abbname": data.abbname,
                                "order_num": data.order_num,
                                "memo": data.memo,
                                "parent_path": data.parentpath,
                                "status": data.status == 0
                            });
                        }
                    });
                }
                else if (obj.event == 'next') {
                    const currentItem = data;
                    const newPath = parent_path ? `${parent_path},${currentItem.id}` : currentItem.id.toString();

                    // 更新路径变量和面包屑
                    parent_path = newPath;
                    breadcrumb.push({
                        id: currentItem.id,
                        name: currentItem.name,
                        path: newPath  // 保存完整路径
                    });

                    // 同步到隐藏字段
                    $("#pid").val(currentItem.id);
                    $("#parent_path").val(newPath);
                    pid = currentItem.id;
                    // 重新加载表格
                    table.reload('LAY-app-area-list', { page: { curr: 1 }, where: { pid: pid } });

                    // 更新区划显示
                    updateBreadcrumb();
                }
                else if (obj.event == 'del') {
                    var msg = data.haschildren ? "当前区划存在子区划，删除时子区划将一并删除，确定删除吗？" : "确定删除吗？";
                    layer.confirm(msg, function (index) {
                        admin.req({
                            url: 'sysarea/deleteareaByID',
                            type: 'delete',
                            data: {
                                id: data.id
                            },
                            contentType: 'application/json',
                            done: function (res) {
                                if (res.successful) {
                                    table.reload('LAY-app-area-list');

                                    admin.msg_success('删除成功！');
                                }
                                else {
                                    admin.msg_error('删除失败！');
                                }
                            }
                        });
                        layer.close(index);
                    });
                }
            });
            /* 导出弹出层 */
            $body.on("click", ".open-popup-export", function () {
                main.exportPopup();
            });

            /* 关闭弹出层 */
            $(".close-popup").click(function (e) {
                e.preventDefault();
                parent.layer.close(window.parent.layerIndex);
            });


        })
    </script>
</body>

</html>